package com.cskaoyan.config;

import com.cskaoyan.shiro.CustomRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

//还没整合暂时注释掉 使用另一个包下的ShiroConfig


// @Configuration
public class ShiroConfig {

    // 默认的SecurityManager
    @Bean
    public DefaultWebSecurityManager securityManagerz(CustomRealm customRealm,DefaultWebSessionManager webSessionManager){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        // 自定义的Realm
        defaultWebSecurityManager.setRealm(customRealm);
        // 默认的Session管理
        defaultWebSecurityManager.setSessionManager(webSessionManager);
        return defaultWebSecurityManager;
    }

    // 过滤器
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManagerz){

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManagerz);

        //单体应用用来配置登录URL用的。还有一个作用：认证失败 → 重定向的请求url → 默认值login.jsp
        shiroFilterFactoryBean.setLoginUrl("/");

        // 使用LinkedHashMap能自定义过滤顺序
        // key：请求url
        // value：过滤器，常见的有anon(匿名)、authc(认证)、perms(授权)
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

        // 配置匿名访问，不需要经过认证和授权。过滤器直接放行
        // 目前放行：登录接口、静态资源
        filterChainDefinitionMap.put("/wx/storage/fetch/**", "anon");
        filterChainDefinitionMap.put("/admin/auth/login", "anon");
//        filterChainDefinitionMap.put("/unAuthc","anon");
//        filterChainDefinitionMap.put("/index","anon");

        // perms：配置哪些url需要权限，配置顺序在认证之前；建议用注解
        //filterChainDefinitionMap.put("/admin/user/list", "perms[user:list]");

        // 配置哪些url需要经过认证
        filterChainDefinitionMap.put("/admin/**","authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    /*
    * 声明式鉴权 注解需要的组件
    * */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManagerz){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManagerz);
        return authorizationAttributeSourceAdvisor;
    }


}
